package com.party.admin.web.controller.mall;

import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.mall.MallShowSubjectBizService;
import com.party.admin.biz.mall.MallShowSubjectTemplateBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.mall.MallShowSubjectTemplateOutput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.mall.MallShowCategory;
import com.party.core.model.mall.MallShowSubject;
import com.party.core.model.mall.MallShowSubjectTemplate;
import com.party.core.model.mall.MallShowSubjectTemplateQuery;
import com.party.core.service.mall.IMallShowCategoryService;
import com.party.core.service.mall.IMallShowSubjectService;
import com.party.core.service.mall.IMallShowSubjectTemplateService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * @Description: 商城导购主题模板
 * @Author: yangshoukun
 * @Date: 2018/4/10 16:31
 */
@Controller
@RequestMapping("/mall/showtemplate")
public class MallShowSubjectTemplateController {

    @Value("#{party['shop.url.protocol']}")
    private String shopUrl;

    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;

    @Autowired
    private MallShowSubjectTemplateBizService mallShowSubjectTemplateBizService;

    @Autowired
    private IMallShowCategoryService mallShowCategoryService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 商品主题分类列表
     *
     * @param templateQuery 主题参数
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView templateList(MallShowSubjectTemplateQuery templateQuery, Page page) {
        ModelAndView mv = new ModelAndView("mall/showTemplateList");
        page.setLimit(10);
        List<MallShowSubjectTemplateOutput> list = mallShowSubjectTemplateBizService.list(templateQuery, page);
        mv.addObject("templates", list);
        mv.addObject("page", page);
        return mv;
    }


    /**
     * 编辑或发布主题分类
     *
     * @param id
     * @return
     */
    @RequestMapping("/templateForm")
    public ModelAndView templateForm(String id) {
        ModelAndView mv = new ModelAndView("mall/showTemplateForm");

        if (StringUtils.isNotEmpty(id)) {
            MallShowSubjectTemplate msst = mallShowSubjectTemplateService.get(id);
            msst.setContent(StringUtils.unescapeHtml4Video2Iframe(msst.getContent()));
            msst.setBuyInstruction(StringUtils.unescapeHtml4Video2Iframe(msst.getBuyInstruction()));
            mv.addObject("template", msst);
        }

        return mv;
    }

    /**
     * 保存主题分类
     *
     * @param mallShowSubjectTemplate
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult saveShowTemplate(MallShowSubjectTemplate mallShowSubjectTemplate) {
        AjaxResult ajaxResult = new AjaxResult();
        //处理富文本
        if (StringUtils.isNotEmpty(mallShowSubjectTemplate.getContent())) {
            String content = StringUtils.escapeHtml4Iframe2Video(mallShowSubjectTemplate.getContent().trim());
            mallShowSubjectTemplate.setContent(content);
        }
        if (StringUtils.isNotEmpty(mallShowSubjectTemplate.getBuyInstruction())) {
            String buyInstruction = StringUtils.escapeHtml4Iframe2Video(mallShowSubjectTemplate.getBuyInstruction().trim());
            mallShowSubjectTemplate.setBuyInstruction(buyInstruction);
        }

        String memberId = RealmUtils.getCurrentUser().getId();
        if (StringUtils.isEmpty(mallShowSubjectTemplate.getId())) {
            mallShowSubjectTemplate.setCreateBy(memberId);
            mallShowSubjectTemplate.setUpdateBy(memberId);
            mallShowSubjectTemplateService.insert(mallShowSubjectTemplate);
        } else {
            mallShowSubjectTemplate.setUpdateBy(memberId);
            mallShowSubjectTemplate.setUpdateDate(new Date());
            mallShowSubjectTemplateService.update(mallShowSubjectTemplate);
        }
        try {
            mallShowSubjectTemplate = mallShowSubjectTemplateService.get(mallShowSubjectTemplate.getId());
            String filePath = fileBizService.getUploadCIPath(mallShowSubjectTemplate.getCreateBy(), MallShowSubjectTemplateBizService.SHOW_SUBJECT_TEMPLATE_FOLDER_NEW);
            String content = "subject?tId=" + mallShowSubjectTemplate.getId();
            content = shopUrl + content;
            fileBizService.uploadCloudOut(mallShowSubjectTemplate.getId(), filePath, content, mallShowSubjectTemplate.getCreateBy(), false);
        } catch (Exception e) {
            logger.error("商品主题分类上传二维码失败, templateId = {}", mallShowSubjectTemplate.getId(), e);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 初始化模板和机构主题的二维码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "initQrCode")
    public String initQrCode() {
        int flag = 0;
        // 初始化template
        List<MallShowSubjectTemplate> templateList = mallShowSubjectTemplateService.listPage(new MallShowSubjectTemplateQuery(), null);
        for (MallShowSubjectTemplate template : templateList) {
            try {
                String filePath = fileBizService.getUploadCIPath(template.getCreateBy(), MallShowSubjectTemplateBizService.SHOW_SUBJECT_TEMPLATE_FOLDER_NEW);
                String content = shopUrl + "subject?tId=" + template.getId();
                fileBizService.uploadCloudOut(template.getId(), filePath, content, template.getCreateBy(), false, 0);
            } catch (Exception e) {
                flag++;
                logger.error("商品主题分类初始化二维码失败, templateId = {}", template.getId(), e);
            }
        }
        // 初始化subject
        List<MallShowSubject> subjectList = mallShowSubjectService.listPage(new MallShowSubject(), null);
        for (MallShowSubject subject : subjectList) {
            try {
                String filePath = fileBizService.getUploadCIPath(subject.getCreateBy(), MallShowSubjectBizService.SHOW_SUBJECT_FOLDER_NEW);
                String content = shopUrl + "subject?id=" + subject.getId();
                fileBizService.uploadCloudOut(subject.getId(), filePath, content, subject.getCreateBy(), false, 0);
            } catch (Exception e) {
                flag++;
                logger.error("上传机构主题二维码失败, subjectId = {}", subject.getId(), e);
            }
        }
        return flag == 0 ? "恭喜初始化成功" : "并未全部成功, 查看日志";
    }

    /**
     * 删除主题分类
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delShowSubjectTemplate(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }

        // 先查询是否存在下级类型
        MallShowCategory categoryParam = new MallShowCategory();
        categoryParam.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        categoryParam.setTemplateId(id);
        List<MallShowCategory> categoryList = mallShowCategoryService.listPage(categoryParam, new Page(1, 1));
        if (CollectionUtils.isNotEmpty(categoryList)) {
            return AjaxResult.error("该主题分类下已有商品类型, 不能删除");
        }

        boolean result = mallShowSubjectTemplateBizService.deleteTemplateBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 复制主题分类
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "copy")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult copyShowSubjectTemplate(String id) {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(false);
        }
        boolean result = mallShowSubjectTemplateBizService.copyTemplateBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("复制失败");
        }
    }

    /**
     * 获取模板数据
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getData")
    public AjaxResult getData(String id) {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(false);
        }
        return mallShowSubjectTemplateBizService.getData(id);
    }
}
